<?php
namespace App\Http\Controllers\Api\V1\Requests;

use App\Models\User;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class FormRequest extends \Illuminate\Foundation\Http\FormRequest
{

   

	public function authorize()
	{
		return true;
	}

    public function failedValidation(Validator $validator)
    {
        $message = '';
        foreach (json_decode(json_encode($validator->errors()),1) as $error){
            $message = $error[0];
            break;
        }
        throw (new HttpResponseException(response()->json([
            'code' => 400,
            'message'  => $message,
            'data' => []
        ],400)));
    }


    public function paycode($isRequired = true)
    {
        $rules = [
            'string',
            'min:6',
            'max:20',
            function ($key, $value, $fail) {

                if (! $value) return true;

                /**
                 * @var User $user
                 */
                $user = request()->user();

                if (! $user->pay_code) {
                    return $fail('请先设置交易密码');
                }

                $payCodeCanTry = (int)sc('pay_code_can_try');

                if ($user->myPayCodeTryCache() >= $payCodeCanTry) {
                    return $fail("交易密码输错{$payCodeCanTry}次请联系客服");
                }

                $payCode = request('pay_code');

                if (!$user->isPayCodeValid($payCode)) {
                    $leftChance = $user->leftPayCodeTryAfterError();
                    return $leftChance > 0
                        ? $fail("交易密码错误，还有{$leftChance}次机会")
                        : $fail("交易密码输错{$payCodeCanTry}次请联系客服");
                }

                return true;
            }
        ];

        if (! $isRequired) {
            $rules[] = 'nullable';
        }

        return $rules;
    }

    public function isFloatValid($value): bool
    {
        if ($value <= 0) return false;

        $regex = '/^((0)|([1-9]\d*))(\.\d{0,2})?$/';

        $match = preg_match($regex, $value);

        return (bool)$match;
    }

    public function isFloatInvalid($value): bool
    {
        return !$this->isFloatValid($value);
    }
}
